import {
	type CanActivate,
	type ExecutionContext,
	Injectable,
} from "@nestjs/common";
import type { Reflector } from "@nestjs/core";
import type { Observable } from "rxjs";

@Injectable()
export class RolesGuard implements CanActivate {
	constructor(private reflector: Reflector) {}

	canActivate(
		context: ExecutionContext,
	): boolean | Promise<boolean> | Observable<boolean> {
		const roles = this.reflector.getAllAndMerge<string[]>("roles", [
			context.getHandler(),
			context.getClass(),
		]);
		if (!roles || roles.length === 0) {
			return true;
		}

		return this.matchRoles(roles);
	}

	private readonly CurrentUserRoles = ["director", "manager"];

	private matchRoles(roles: string[]): boolean {
		for (const role of roles) {
			if (this.CurrentUserRoles.includes(role)) {
				return true;
			}
		}
		return false;
	}
}
